package org.totoro.boot.springmvc.web;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017/7/19.
 */
@Service
public class HandlerAdapterInterface  implements HandlerAdapter, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public boolean supports(Object handler) {

        return (handler instanceof HandlerMethod);
    }

    @Override
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod= (HandlerMethod) handler;

        RequestMappingHandlerAdapter requestMappingHandlerAdapter = applicationContext.getBean("requestMappingHandlerAdapter", RequestMappingHandlerAdapter.class);

        ModelAndView handle = requestMappingHandlerAdapter.handle(request, response, handler);


        return  handle;

    }

    @Override
    public long getLastModified(HttpServletRequest request, Object handler) {
        return 0;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext=applicationContext;
    }
}
